package com.hejia.alauda.service;

import com.hejia.alauda.entity.*;
import com.hejia.alauda.entity.example.BalanceOperationExample;
import com.hejia.alauda.entity.example.BonusReceiveExample;
import com.hejia.alauda.entity.example.FinancingExample;
import com.hejia.alauda.entity.example.InvitationExample;
import com.hejia.alauda.persistence.mybatis.*;
import com.hejia.alauda.utils.Encryption;
import com.hejia.alauda.utils.Pager;
import com.hejia.alauda.utils.Utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.math.BigDecimal;
import java.util.*;

import static org.apache.commons.lang3.time.DateUtils.addDays;
import static org.springframework.util.CollectionUtils.isEmpty;

@Service
@Deprecated
public class ApiServiceImpl implements ApiService {
	
	static final Log logger = LogFactory.getLog(ApiService.class);
	
	public static final String KEY_SHARE = "hejiajinrong_share_%s_%s";
	
	@Resource
	private InterestMapper interestMapper;
	
	@Resource
	private FinancingMapper financingMapper;
	
	@Resource
	private ProductMapper productMapper;
	
	@Resource
	private BalanceOperationMapper balanceOperationMapper;
	
	@Resource
	private InvitationMapper invitationMapper;
	
	@Resource
	private BonusReceiveMapper bonusReceiveMapper;
	
	@Resource
	private BonusRecordMapper bonusRecordMapper;
	
	@Resource
	private UserService userService;
	
	@Resource
	private RedisTemplate<String, Object> redisTemplate;
	
	@Override
	public Pager findInterestPagination(Map<String, Object> params, Pager pager) {
		pager.setList(interestMapper.findInterestList(params, pager));
		pager.setTotalCount(interestMapper.findCountInterestList(params));
		return pager;
	}

	@Override
	public Pager findInvestmentPagination(Map<String, Object> params, Pager<Map<String,Object>> pager) {
		pager.setList(financingMapper.findInvestment(params, pager));
		pager.setTotalCount(financingMapper.findInvestmentCount(params));
		/*判断状态*/
		if(!isEmpty(pager.getList())){
			for(Map<String, Object> item : pager.getList()){
				Date expiredDate = addDays((Date)item.get("settlementDate"), -1);
				Financing.Status status = Financing.Status.valueOf((String)item.get("status"));
				String statusStr = Financing.getStatusStr(expiredDate, status);
				item.put("status", statusStr);
				if("已兑付".equals(statusStr)){
					item.put("color", "32CD32");
				} else if("兑付中".equals(statusStr)){
					item.put("color", "E08002");
				} else {
					item.put("color", "FF0000");
				}
			}
		}
		return pager;
	}

	@Override
	public Pager<Map<String, Object>> findCurrentInterestList(
			Map<String, Object> params, Pager<Map<String, Object>> pager) {
		pager.setList(interestMapper.findCurrentInterestList(params, pager));
		pager.setTotalCount(interestMapper.findCurrentInterestListCount(params));
		return pager;
	}

	@Override
	public List<Product> findProductsPagination(Map<String, Object> params,
			Pager<Product> pager) {
//		List<Product> list = productMapper.findProducts(params, pager);
//		for(Product product : list) {
//			FinancingExample financingExample = new FinancingExample();
//			financingExample.appendCriterion("product_id=", product.getId());
//			product.setNumberOfShoppers(financingMapper.countByExample(financingExample));
//		}
		return productMapper.findProducts(params, pager);
	}

	@Override
	public int findProductsCountPagination(Map<String, Object> params) {
		return productMapper.findProductsCount(params);
	}

	@Override
	public String findInterestSum(Map<String, Object> params) {
		return interestMapper.findInterestSum(params);
	}

	@Override
	public Pager<BalanceOperation> findBalanceOperationsPagination(
			BalanceOperationExample example, Pager<BalanceOperation> pager) {
		pager.setList(balanceOperationMapper.selectByExample(example, pager));
		pager.setTotalCount(balanceOperationMapper.countByExample(example));
		return pager;
	}

	@Override
	public List<Map<String, Object>> findCreditInvitation(
			Map<String, Object> params) {
		return invitationMapper.findCreditInvitation(params);
	}

	@Override
	public Integer countFinancingByUser(User user) {
		FinancingExample example = new FinancingExample();
		example.appendCriterion("user_id=", user.getId());
		return financingMapper.countByExample(example);
	}
	
	@Transactional
	@Override
	public int saveBonusReceive(BonusReceive entity) {
//		int result = bonusReceiveMapper.insert(entity);
//		if(result>0){
//			//afterSaveBonusReceive(entity);
//			MessageEvent event = new MessageEvent(EventConstant.KEY_ADD_BONUS_RECEIVE_EVENT, entity.getId());
//			CommonServiceImpl.applicationContext.publishEvent(event);
//		}
		return bonusReceiveMapper.insert(entity);
	}

	public List<BonusReceive> findBonusReceiveByExample(BonusReceiveExample example, Pager<BonusReceive> pager) {
		return this.bonusReceiveMapper.selectByExample(example != null ? example : new BonusReceiveExample(), pager);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Map<String, Object>> findReceiver(String mobile) {
		BonusReceiveExample bonusReceiveExample = new BonusReceiveExample();
		bonusReceiveExample.appendCriterion("sharer<>receiver");
		bonusReceiveExample.appendCriterion("sharer=", mobile);
		List<BonusReceive> bonusReceives = bonusReceiveMapper.selectByExample(bonusReceiveExample, null);
		if(isEmpty(bonusReceives)){
			return java.util.Collections.EMPTY_LIST;
		}
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>(bonusReceives.size());
		for (BonusReceive item : bonusReceives) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("date", Utils.formatDate(item.getCreateDate()));
			map.put("mobile", Encryption.obfuscatedMobile(item.getReceiver()));
			map.put("amount", item.getAmount());
			/**
			 * 判断是否邀请手机号注册状态
			 */
			if(userService.findUserCountByMobile(item.getReceiver())==0){
				map.put("status","未注册");
			} else {
				User receiver = userService.findUserByMobile(item.getReceiver());
				map.put("status",countFinancingByUser(receiver)>0?"已交易":"未交易");
			}
			list.add(map);
		}
		return list;
	}

	@Override
	public List<Map<String, Object>> findRewardAmount(Map<String, Object> params) {
		return bonusReceiveMapper.findRewardAmount(params);
	}

	@Override
	public Map<String, Object> getRewardAmount(String mobile, List<Map<String, Object>> list) {
		BigDecimal total = new BigDecimal("0");
		BigDecimal cashed = new BigDecimal("0");
		List<Map<String, Object>> results = new ArrayList<Map<String,Object>>();
		/**
		 * 先计算自己领取的部分
		 */
		BonusReceiveExample bonusReceiveExample = new BonusReceiveExample();
		bonusReceiveExample.appendCriterion("receiver=", mobile);
		
		BonusReceive selfBonus = this.bonusReceiveMapper.selectOneByExample(bonusReceiveExample);
		if(selfBonus!=null){
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("date", Utils.formatDate(selfBonus.getCreateDate()));
			map.put("amount", selfBonus.getAmount());
			map.put("status","主动领取");
			total = total.add(selfBonus.getAmount());
			/**
			 * 判断是否已经提取过
			 */
			if(selfBonus.getBonusRecord()!=null && selfBonus.getBonusRecord().getConsume()){
				cashed = cashed.add(selfBonus.getAmount());
			}
			results.add(map);
		}
		
		bonusReceiveExample = new BonusReceiveExample();
		bonusReceiveExample.appendCriterion("rewardAmount=",10);
		bonusReceiveExample.appendCriterion("sharer<>receiver");
		bonusReceiveExample.appendCriterion("sharer=", mobile);
		List<BonusReceive> blist = bonusReceiveMapper.selectByExample(bonusReceiveExample, null);
		if(!isEmpty(blist)){
			for(BonusReceive item : blist){
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("date", Utils.formatDate(item.getCreateDate()));
				map.put("amount", item.getRewardAmount());
				map.put("status","主动领取");
				total = total.add(item.getRewardAmount());
				/**
				 * 判断是否已经提取过
				 */
				if(item.getBonusRecord()!=null && item.getBonusRecord().getConsume()){
					cashed = cashed.add(item.getRewardAmount());
				}
				results.add(map);
			}
		}
		
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("total", total);
		data.put("cashed", cashed);
		return data;
	}

	@Override
	public List<Invitation> findInvitationByExample(InvitationExample example) {
		return this.invitationMapper.selectByExample(example, null);
	}

	@Override
	public List<Map<String, Object>> findInvitionWithBouns(Map<String, Object> params) {
		return invitationMapper.findInvitationWithBonus(params);
		
	}

}
